package com.example.springboot_sp.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot_sp.common.Result;
import com.example.springboot_sp.mapper.WordMapper;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.example.springboot_sp.service.IWordService;
import com.example.springboot_sp.entity.Word;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 郭守军
 * @since 2022-08-18
 */
@RestController
@RequestMapping("/word")
                public class WordController {

        @Resource
        private IWordService wordService;

        // 新增或者更新
        @PostMapping
        public Result save(@RequestBody Word word) {
                return Result.success(wordService.saveOrUpdate(word));
                }

        @DeleteMapping("/{id}")
        public Result delete(@PathVariable Integer id) {
                return Result.success(wordService.removeById(id));
                }

        @PostMapping("/del/batch")
        public Result deleteBatch(@RequestBody List<Integer> ids) {
                return Result.success(wordService.removeByIds(ids));
                }

        @GetMapping
        public Result findAll() {
                return Result.success(wordService.list());
                }

        @GetMapping("/{id}")
        public Result findOne(@PathVariable Integer id) {
                return Result.success(wordService.getById(id));
                }

        @GetMapping("/unWord/{know}")
        public Result know(@PathVariable Integer know) {
                return Result.success(wordService.getByknow(know));
        }

        //添加不认识的单词
        @GetMapping("/unknown")
        public void updateKnow(@RequestParam  String word )
        {
                wordService.updateKnow(word);
        }
        //假删除不认识的单词
        @GetMapping("/unknownDlete")
        public void unknownDlete(@RequestParam  String word )
        {
                wordService.unknownDlete(word);
        }

        @GetMapping("/page")
        public Result findPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam(defaultValue = "") String word,
                               @RequestParam(defaultValue = "") String part,
                               @RequestParam(defaultValue = "") String mean,
                               @RequestParam(defaultValue = "") String unit,
                               @RequestParam(defaultValue = "") String gride) {
                QueryWrapper<Word> queryWrapper = new QueryWrapper<>();
        if (!"".equals(word)) {
                queryWrapper.like("word", word);
        }
        if (!"".equals(part)) {
                queryWrapper.like("part", part);
        }
        if (!"".equals(mean)) {
                queryWrapper.like("mean", mean);
        }
        if (!"".equals(unit)) {
                queryWrapper.like("unit", unit);
        }
        if (!"".equals(gride)) {
                queryWrapper.like("gride", gride);
        }
        queryWrapper.orderByDesc("id");

        return Result.success( wordService.page(new Page<>(pageNum, pageSize), queryWrapper));
        }
        /**
         * 批量导出接口
         */
        @GetMapping("/export")
        public void export(HttpServletResponse response) throws Exception {
                // 从数据库查询出所有的数据
                List<Word> list = wordService.list();
                // 通过工具类创建writer 写出到磁盘路径
                //ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/单词列表.xlsx");
                // 在内存操作，写出到浏览器
                ExcelWriter writer = ExcelUtil.getWriter(true);
                //自定义标题别名
                writer.addHeaderAlias("word", "单词");
                writer.addHeaderAlias("part", "词性");
                writer.addHeaderAlias("mean", "词义1");
                writer.addHeaderAlias("mean2", "词义2");
                writer.addHeaderAlias("mean3", "词义3");
                writer.addHeaderAlias("gride", "分类");
                writer.addHeaderAlias("createTime", "创建时间");
                // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
                writer.write(list, true);

                // 设置浏览器响应的格式
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
                String fileName = URLEncoder.encode("单词列表", "UTF-8");
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

                ServletOutputStream out = response.getOutputStream();
                writer.flush(out, true);
                out.close();
                writer.close();
        }

        /**
         * excel 批量导入
         * @param file
         * @throws Exception
         */
        @PostMapping("/import")
        public Result imp(MultipartFile file) throws Exception {
                InputStream inputStream = file.getInputStream();
                ExcelReader reader = ExcelUtil.getReader(inputStream);
                // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
                // List<User> list = reader.readAll(User.class);
                // 方式2：忽略表头的中文，直接读取表的内容
                List<List<Object>> list = reader.read(1);
                List<Word> words = CollUtil.newArrayList();
                for (List<Object> row : list) {
                        Word word = new Word();
                        word.setWord(row.get(1).toString());
                        word.setPart(row.get(2).toString());
                        word.setMean(row.get(3).toString());
                        word.setMean2(row.get(4).toString());
                        word.setMean3(row.get(5).toString());
                        word.setGride(row.get(6).toString());
                        words.add(word);
                }
                wordService.saveBatch(words);
                return Result.success(true);
        }

}

